import json
from pathlib import Path
from typing import Any, Dict, Optional, TypedDict


class AutoDeliverConfigType(TypedDict):
    task_count: int
    salary_filter: str
    job_keywords: list[str]
    location_keywords: list[str]
    csv_enable: bool
    adb_path: str
    scrcpy_path: str


class AutoDeliverConfig:
    def __init__(self) -> None:
        self._default_config: AutoDeliverConfigType = {
            "task_count": 10,
            "salary_filter": "8000-15000",
            "job_keywords": ["Python", "测试", "运维"],
            "location_keywords": ["广州", "深圳"],
            "csv_enable": True,
            "adb_path": "..\\python-embed\\Lib\\site-packages\\airtest\\core\\android\\static\\adb\\windows\\adb.exe",
            "scrcpy_path": "scrcpy-win64-v3.1"
        }

        # self._config_path: Path = Path.home() / ".auto_deliver" / "config.json"
        self._config_path: Path = Path("config.json")
        self._config: AutoDeliverConfigType = self._load_config()

    def _load_config(self) -> AutoDeliverConfigType:
        if not self._config_path.exists():
            print(f"配置文件不存在：{self._config_path}，使用默认配置")
            return self._default_config.copy()

        try:
            with open(self._config_path, 'r', encoding='utf-8') as f:
                data: Dict[str, Any] = json.load(f)
            return self._validate_config(data)
        except Exception as e:
            print(f"加载配置失败：{e}，使用默认配置")
            return self._default_config.copy()

    def _validate_config(self, cfg: Dict[str, Any]) -> AutoDeliverConfigType:
        validated = self._default_config.copy()
        for key, value in cfg.items():
            if key in validated and isinstance(value, type(validated[key])):
                validated[key] = value
            else:
                print(f"配置项 {key} 类型错误或无效，使用默认值")
        return validated

    def save_config(self) -> bool:
        try:
            self._config_path.parent.mkdir(parents=True, exist_ok=True)
            with open(self._config_path, 'w', encoding='utf-8') as f:
                json.dump(self._config, f, indent=4, ensure_ascii=False)
            return True
        except Exception as e:
            print(f"保存配置失败: {e}")
            return False

    def get(self, key: str, default: Optional[Any] = None) -> Any:
        return self._config.get(key, default)

    def set(self, key: str, value: Any) -> bool:
        if key in self._default_config and isinstance(value, type(self._default_config[key])):
            self._config[key] = value
            return True
        print(f"尝试设置无效的配置项: {key}")
        return False

    def get_all(self) -> AutoDeliverConfigType:
        return self._config.copy()

    def reload(self) -> None:
        self._config = self._load_config()
